var ctx=window.daijia.ctx;
var lng=window.daijia.lng;
var lat=window.daijia.lat;
var address = window.daijia.address;
var allmap2=null;//专车地图对象
var freight_map2=null;
var freight_driving=null;
var freight_points=[];
var pointObj=[];
var myGeo=null;
var index = 0;
var polylines=[];
var start = new Array();
var end = new Array();
var way=new Array();
var distance=[];
var timeStr=[];
var flag=true;
var last=false;
var tempmarkers=[];
var count=0;
var pointIndex=1;
var zj_input=null;
var isBlack=false;
function freight_initialize(){
	 myGeo = new BMap.Geocoder();
	 var point=new BMap.Point(lng,lat);	
	 myGeo.getPoint(address, function(po){
		 if (po) {
				freight_map2 = new BMap.Map("freight_allmap");
				freight_map2.centerAndZoom(po, 13);
			    freight_map2.enableScrollWheelZoom();
			    ///三种驾车策略：最少时间，最短距离，避开高速    BMAP_freight_driving_POLICY_LEAST_TIME,BMAP_freight_driving_POLICY_LEAST_DISTANCE,BMAP_freight_driving_POLICY_AVOID_HIGHWAYS
			    freight_driving = new BMap.DrivingRoute(freight_map2, {policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE});
			    freight_driving.setSearchCompleteCallback(function(){
			        var pts = freight_driving.getResults().getPlan(0).getRoute(0).getPath(); //通过驾车实例，获得一系列点的数组
			        var plan = freight_driving.getResults().getPlan(0);
			        distance[distance.length]=plan.getDistance(true);
			        timeStr[timeStr.length]=plan.getDuration(true);
			        
			        var polyline = new BMap.Polyline(pts);  
			        polylines[polylines.length]=polyline;
			        freight_map2.addOverlay(polyline);
			        if(flag){
			        	bdGEO();
			        	flag=false;
			        }
			       setTimeout(function(){
			            freight_map2.setViewport(freight_points); 
			            //调整到最佳视野
			            $("#truckTypeId").change();
			        },200);
			    });
			   
			    //右键菜单
			    var contextMenu = new BMap.ContextMenu();
				var txtMenuItem = [{
				   text:'设为始发地',
				   callback:function(p){
					   index=0;
					   flag=true;
					   pointObj=[];
					   if(freight_points[0]!=undefined){
			    		   freight_points.splice(0,1,p);
			    	   }else{
			    		   freight_points[0]=p;
			    	   }
					   if(freight_points.length==1){
						   getFreightEmployee();
						    var marker = new BMap.Marker(p); 
					        myGeo.getLocation(p, function(rs){
								   var addComp = rs.addressComponents;
								   var address=addComp.district + " "+ addComp.street;
								    var lab = new BMap.Label(address,{offset:new BMap.Size(-30,-15)});
									lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
									marker.setLabel(lab); 
									$("#freight_startAddress").val(address);
									$("#freight_startAddress").attr("waypointlng",p.lng);
									$("#freight_startAddress").attr("waypointlat",p.lat);
							    }); 
					            freight_map2.clearOverlays();       
							    freight_map2.addOverlay(marker);
					   
					   }else if(freight_points.length>1){
						   
						   index=0;
						   flag=true;
						   distance=[];
						   timeStr=[];
						   myGeo.getLocation(p, function(rs){
							   var addComp = rs.addressComponents;
							   var address=addComp.district + " "+ addComp.street;
								$("#freight_startAddress").val(address);
								$("#freight_startAddress").attr("waypointlng",p.lng);
								$("#freight_startAddress").attr("waypointlat",p.lat);
						    }); 
						   freight_map2.clearOverlays();           
							  for(var i=0;i<freight_points.length-1;i++){
								  freight_driving.search(freight_points[i],freight_points[i+1]);
							  }	
					   }
					   
				   }
				},{
				   text:'设为途径地',
				   callback:function(p){
					   if(freight_points.length==12){
						   $.scojs_message("最多只能添加十个途径地", $.scojs_message.TYPE_ERROR);
						   
						   return;
					   }
					   
					   
					   if(freight_points.length>0){
						   index=0;
						   flag=true;
						   distance=[];
						   timeStr=[];
						   
						   
						   freight_points[freight_points.length]=p;
						   freight_map2.clearOverlays();           
							  for(var i=0;i<freight_points.length-1;i++){
								  freight_driving.search(freight_points[i],freight_points[i+1]);
							  }	
						   var end = $("#freight_destination");
						   var marker = new BMap.Marker(p); 
						   if(end.val()==""){
							   myGeo.getLocation(p, function(rs){
								   var addComp = rs.addressComponents;
								   var address=addComp.district + " "+ addComp.street;
								   var lab = new BMap.Label(address,{offset:new BMap.Size(-30,-15)});
									lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
									marker.setLabel(lab); 
									end.val(address);
									end.attr("waypointlng",p.lng);
									end.attr("waypointlat",p.lat);
							    }); 
					       
							    freight_map2.addOverlay(marker);  
							   
							   
						   }else{

								count++;
								  myGeo.getLocation(p, function(rs){
									   var addComp = rs.addressComponents;
									   var address=addComp.district + " "+ addComp.street;
									  
									   
									   var str = "<div class='form-group wayAddress' id='waypoint"+count+"'>"+
								         "<div class='col-sm-9'>"+
								                 	"<div class='input-group '>"+
								                 		"<span class='input-group-addon'>途径地址</span>"+
										            		 "<input class='form-control waypointAddress' onfocus='showData(this)' index="+(++pointIndex)+" waypointLng='' waypointLat='' id='address"+count+"'/>"+
									                "</div>"+
									                "<div class='show'><font style='font-size:10px'> 联系人:<span class='showContacts'></span></font> <font style='font-size:10px'>联系电话:<span class='showPhone'></span></font></div>"+
									                "<div class='col-sm-12' style='display:none;'>"+
								                     "<div class='input-group col-sm-12'>"+
								                 	   "<span class='input-group-addon'>联系人员</span>"+
										            	    "<input class='form-control waypointContacts' />"+
									                 "</div>"+
									                "</div>"+
									                "<div class='col-sm-12' style='display:none;'>"+
								                      "<div class='input-group col-sm-12'>"+
								                 	    "<span class='input-group-addon'>联系电话</span>"+
										            	    "<input class='form-control waypointPhone'  required/>"+
									                	"</div>"+
									                "</div>"+
								        "</div>"+
								      "<div class='input-group'>"+
					               	 	"<label><span class='glyphicon glyphicon-minus waypointIcon subWaypoint' style='cursor:pointer;' title='删除途径地' index='waypoint"+count+"'></span></label>"+
					             	   	"</div>"+
					             "</div>";
								
										    //"<div class='input-group'>"+
						               	     //  "<label><i class=' icon-plus icon-1x waypointIcon addWaypoint'  style='cursor:pointer;' title='添加途径地' index='waypoint"+count+"'></i></label>"+
						               	   // "</div>"+
						               	
									   
								 $("#waypointItem").append(str); 
								 $(".subWaypoint").unbind().click(function(){
									 count--;
									 pointIndex--;
									 
										$(this).parent().parent().parent().remove();
										var index1 = end.attr("index");
										end.attr("index",index1-1);
										/*
										var p1 = new BMap.Point(start[0],start[1]);
										var p2 = new BMap.Point(end[0],end[1]);
										freight_driving.search(p1, p2,{waypoints:way});
										//$('#'+index).remove();
										*/
										var arr = $(".subWaypoint");
										for(var i=0;i<arr.length;i++){
											$(arr[i]).attr("index",("waypoint"+(i+1)));
										}
										var arr = $(".wayAddress");
										for(var i=0;i<arr.length;i++){
											if(i==0){
												$(arr[i]).attr("id",("start"));
											}else if(i==(arr.length-1)){
												$(arr[i]).attr("id",("end"));
											}else{
												$(arr[i]).attr("id",("waypoint"+(i)));
											}
										}
										var address = $(".waypointAddress");
										for(var i=0;i<address.length;i++){
											$(address[i]).attr("index",i);
										}
										var temp = $(this).parent().parent().parent().find(".waypointAddress").attr("index");
										freight_points.splice(temp,1);
										 freight_map2.clearOverlays();
										 flag=true;
										  index=0;
										  distance=[];
										  timeStr=[];
										 for(var i=0;i<freight_points.length-1;i++){
											  freight_driving.search(freight_points[i],freight_points[i+1]);
										  }	 
										 
										 
								  });
								 
								 var address1=end.val();
									end.val(address);
									var lng=end.attr("waypointLng");
									end.attr("waypointLng",p.lng);
									var lat=end.attr("waypointLat");
									end.attr("waypointLat",p.lat);
									var phone=$("#end").find("#phone").val();
									$("#end").find("#phone").val("");
									$("#end").find(".showPhone").empty();
									var contacts=$("#end").find("#contacts").val()
									$("#end").find("#contacts").val("");
									$("#end").find(".showContacts").empty();
									var way = $("#waypoint"+count);
									way.find(".waypointAddress").val(address1);
									way.find(".waypointAddress").attr("waypointLng",lng);
									way.find(".waypointAddress").attr("waypointLat",lat);
									way.find(".waypointContacts").val(contacts);
									way.find(".waypointPhone").val(phone);
									way.find(".showContacts").text(contacts);
									way.find(".showPhone").text(phone);
									var index2 = way.find(".waypointAddress").attr("index");
									var index1 = end.attr("index");
									way.find(".waypointAddress").attr("index",index1);
									end.attr("index",index2);
								    });
								 
					         }
						   
					     }  
					   }
					   
				}];
				
				for(var i=0; i < txtMenuItem.length; i++){
					contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
					if(i==1 || i==3) {
						contextMenu.addSeparator();
					}
				}
				freight_map2.addContextMenu(contextMenu); 
				

			    //地图加载完毕
			   
			}
			else{
				$.scojs_message("地区"+center+"位置不准确，请重新编辑地区", $.scojs_message.TYPE_ERROR);
			}
	 });
	 
	

}
function bdGEO(){	
	var pt = freight_points[index];
	geocodeSearch(pt);
	
	index++;
}
function geocodeSearch(pt){
	if(index < freight_points.length-1){
		setTimeout(window.bdGEO,600);
	} 
	myGeo.getLocation(pt, function(rs){
		var addComp = rs.addressComponents;
		var m = new BMap.Marker(pt);
		tempmarkers[tempmarkers.length]=m;
		var  str= addComp.district + " " + addComp.street;
		var lab = new BMap.Label(str,{offset:new BMap.Size(-30,-15)});
		lab.setStyle({ color : "#ED2D2D", fontSize : "16px",border:"0" });
		m.setLabel(lab);
		freight_map2.addOverlay(m);
	});
	 
}


function position(address){
	 if(($(address).parent().parent().parent().parent().parent().parent().parent()).prev().attr("id")!=null&&($(this).parent().parent().parent().parent().parent().parent().parent()).prev().find($(".waypointAddress")).val()==""){
		 $.scojs_message("请从上一个途径地开始填写", $.scojs_message.TYPE_ERROR);
		 return false;
	 };
	var tempIndex=parseInt($(address).attr("index"));
	if($(address).val()==''){
		$.scojs_message("请填写地点", $.scojs_message.TYPE_ERROR);
	}else{
		freight_map2.clearOverlays();
		var local = new BMap.LocalSearch(freight_map2, {
			renderOptions:{map: freight_map2, autoViewport:true}
		});
		
		var length = freight_points.length;
		local.search($(address).val());
		local.setInfoHtmlSetCallback(function(poi,marker,html){
			 
			 var str = ($(html).text().substr(4).split("电话"))[0];
	    	   var string;
	    	   if(str.indexOf("段")==-1){
		    		  if(str.indexOf("路")==-1){
		    			  if(str.indexOf("街")==-1){
		    				  if(str.indexOf("号")==-1){
		    					  string =str;
		    				  }else{
		    					  string=str.substring(0,str.indexOf(/\d+号/.exec(str)[0]));
		    				  }
		    			  }else{
		    				 string = str.substring(0,str.indexOf("街")+1);
		    			  }
		    		  }else{
		    			  string = str.substring(0,str.indexOf("路")+1);
		    		  }
		    	   }else{
		    		   string = str.substring(0,str.indexOf("段")+1);
		    	   }	
	    	   $(address).val(string+poi.marker.getTitle());
	    	   $(address).attr("waypointLng",poi.marker.point.lng);
	    	   $(address).attr("waypointLat",poi.marker.point.lat);
	    	   index=0;
	    	   flag=true;
	    	   if(freight_points[tempIndex]!=undefined){
	    		   freight_points.splice(tempIndex,1,poi.point);
	    	   }else{
	    		   freight_points[length]=poi.point;
	    	   }
			 //  points[length]=poi.point;
			   
	    	   if(freight_points.length==1){
					 var markers = freight_map2.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
			   }else if(freight_points.length>1){
				   var markers = freight_map2.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
					for(var i=0;i<tempmarkers.length;i++){
						tempmarkers[i].hide();
					}
					poi.marker.hide(); 
					for(var j=0;j<polylines.length;j++){
						freight_map2.removeOverlay(polylines[j]);
					}
					
					
					 distance=[];
					 timeStr=[];
				  for(var i=0;i<freight_points.length-1;i++){
					  freight_driving.search(freight_points[i],freight_points[i+1]);
				  }	 
				 
			   }
	    	   
	    });
	}

}
function showData(add){
	tempInput = $(add).parent().parent();
	$('#myModal').modal({backdrop:true});
	$("#Address").val($(add).parent().parent().find(".waypointAddress").val());
    $("#tempContacts").val($(add).parent().parent().find(".waypointContacts").val());
    $("#tempPhone").val(($(add).parent().parent().find(".waypointPhone")).val());
}
//推荐附近员工
function getFreightEmployee(){
	    if($("#truckTypeId").val()==""){
	    	$("#freight_tbodyId").empty();
	    }else{
	    	$.get(ctx+'/freight/getEmployees',{
		    	startLat:freight_points[0].lat,
		    	startLng:freight_points[0].lng,
		    	truckTypeId:$("#truckTypeId").val()
		    	},function(data){
		    	$(".freight_drivers-tr").remove();
				if(data && data.length>0){
					$(data).each(function(i,driver){
						var content="<tr class='freight_drivers-tr'>"+
									"<td><input type='radio' name='freihgt_checkDriver' value='"+driver.employId+"' /></td>"+
									"<td>"+driver.employName+"</td>"+
									"<td>"+driver.carNumber+"</td>"+
									"<td>"+driver.distance+"</td>"+
									"<tr>";
						$("#freight_tbodyId").append(content);
					});
				}
			});
	    }
}

function loadTruckType(){
	var select = $("#truckTypeId");
	if($("#freight_companyId").val()!=""){
	$.get(ctx+'/freight/findByTruckTypeCompanyId',{'companyId':$("#freight_companyId").val()},function(data){
	    select.children('option').remove();
	    var truckTypes = data.truckTypes;
	    if(truckTypes.length==0){
	    	select.children('option').remove()
			var content = "<option value=''>此公司没有货车类型</option>";
	    	select.append($(content));
	    	$("#budgetPay").val("");
	    	$("#startPrice").val("");
	    	$("#mileagePrice").val("");
	    	$("#runTimePrice").val("");
	    	$("#runTime").val("");
	    	$("#mileage").val("");
	    	$(".runTime").text("");
	    	$(".mileage").text("");
	    }
	    for(var i=0;i<truckTypes.length;i++){
	    	
	    	var str = '';
	    	if(truckTypes[i].cangointotown){
	    		str='--入城';
	    	}
	    	var content = "<option value='"+truckTypes[i].id+"'>"+truckTypes[i].typeName+str+"</option>";
	    	select.append($(content));
	    	$("#truckTypeId").change();
	    }
		
	},'json');
	}else{
		select.children('option').remove()
		var content = "<option value=''>请先选择公司</option>";
    	select.append($(content));
	}
	
	
}
$(document).ready(function(){
	$.get(ctx+'/member/findByPhone',{'phone':$("#freight_passengerPhone").val(),'couponType':'freight'},function(data){
		if(data.passenger!=null){
			$("#freight_membertype").text("");
			$("#freight_companyName").val(data.passenger.companyName);
			$("#freight_passengerId").val(data.passenger.id);
			$("#freight_passengerName").val(data.passenger.name);
			$("#start").find(".waypointContacts").val(data.passenger.name);
			$("#start").find(".waypointPhone").val(data.passenger.phone);
			$("#start").find(".showContacts").text(data.passenger.name);
			$("#start").find(".showPhone").text(data.passenger.phone);
			if(data.passenger.inBlackList){
				$("#freight_membertype").html("黑名单");
				isBlack=true;
			}else{
				$("#freight_membertype").html(data.passenger.typeStr+(data.passenger.grade_name==null?"":("-"+data.passenger.grade_name)));
			}
			$("#freight_clientVirtual").text(data.passenger.drawMoney+"元");
			$("#freight_companyId option").each(function(index,element){
			  	if($(element).attr("value")==data.passenger.companyId){
			 		$(element).attr("selected","selected");
			 		$("#freight_companyId").change();
			 		return false;
			 	}
			});
			if(data.coupons!=null&&data.coupons.length>0){
				var text="";
				for(var i=0;i<data.coupons.length;i++){
					if(data.coupons[i].couponRule.couponType=="freight"){
						text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
					}
				}
				$("#freight_couponId").empty();
				if(text!=""){
					$("#couponInput").css("display","block");
					$("#freight_couponId").append(text);
				}
			}else{
				$("#couponInput").css("display","none");
				$("#freight_couponId").empty();
			}
		}else{
			$("#couponInput").css("display","none");
			$("#freight_couponId").empty();
			$("#freight_membertype").text("新客户");
			$("#freight_passengerName").val("先生/女士");
			$("#start").find(".waypointContacts").val($("#freight_passengerName").val());
			$("#start").find(".waypointPhone").val($("#freight_passengerPhone").val());
			$("#start").find(".showContacts").text($("#freight_passengerName").val());
			$("#start").find(".showPhone").text($("#freight_passengerPhone").val());
		}
		
	});


	$("#freight_startTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true,startDate:new Date()});
	$("#freight_startTime").val(new Date(new Date().getTime()+1000*60*3).Format("yyyy-MM-dd hh:mm"));
	var f=false;
	var g=false;
	var z=false;
	var flitting=false;
	var receipt=false;
	var receivedPay=false;
	
	$('#payMount').bind('input propertychange', function() {
		var val = $(this).val();
		var p = val.split(".");
		if(window.parseFloat($(this).val())>window.parseFloat($(this).attr("max"))){
	      $.scojs_message('输入数值过大', $.scojs_message.TYPE_ERROR);
	      $(this).val("");
	    }else if(window.parseFloat($(this).val())<1){
	        $.scojs_message('输入数值过小', $.scojs_message.TYPE_ERROR);
	        $(this).val("");
	    }
		if(p.length>1){
	    	if(p[1].length>2){
	    		 $.scojs_message('小数位数限定为两位小数', $.scojs_message.TYPE_ERROR);
	    		 $(this).val(p[0]+"."+p[1].substr(0,2));
	    	}
	    }
	    
	});
	$("input[name=receivedPay]").click(function(){
		if(!receivedPay){
			
			$(".receivedPay").css("display","inline-block ");
			receivedPay=true;
		}else{
			receivedPay=false;
			$(".receivedPay").css("display","none");
		}
		
	});
	$("input[name=receipt]").click(function(){
		if(!receipt){
			
			
			receipt=true;
		}else{
			receipt=false;
		}
		
	});$("input[name=flitting]").click(function(){
		if(!flitting){
			
			flitting=true;
		}else{
			flitting=false;
			
		}
		
	});
	$("#freightClick").click(function(){
		freight_initialize();
	});

$("#tempContacts").change(function(){
	tempInput.find(".waypointContacts").val($("#tempContacts").val());
	tempInput.find(".showContacts").text($("#tempContacts").val());
});
$("#tempPhone").change(function(){
	tempInput.find(".waypointPhone").val($("#tempPhone").val());
	tempInput.find(".showPhone").text($("#tempPhone").val());
});
	freight_initialize();
	loadTruckType();
	$(window).scroll(function(){  
		$("#freight_allmap").css({ position:'fixed',left:'20px',top:'53px',width:'554px'});
	});
	$(".addAddress").click(function(){
		last=false;
		if($("#freight_destination").val()==""){
			$.scojs_message("请依次填写地址", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($(".wayAddress").length>=12){
			$.scojs_message("最多只能添加十个途径地", $.scojs_message.TYPE_ERROR);
			return;
		}
		if(!($(".wayAddress").length>0)){
			count=0;
		}
		count++;
		var content = "<div class='form-group wayAddress' id='waypoint"+count+"'>"+
				         "<div class='col-sm-9'>"+
				                 	"<div class='input-group'>"+
				                 		"<span class='input-group-addon'>途径地址</span>"+
						            	 "<input class='form-control waypointAddress'  index="+(++pointIndex)+" waypointLng='' onfocus='showData(this)' waypointLat='' id='address"+count+"'/>"+
					                "</div>"+
					                "<div class='show'><font style='font-size:10px'> 联系人:<span class='showContacts'></span></font> <font style='font-size:10px'>联系电话:<span class='showPhone'></span></font></div>"+
					                "<div class='col-sm-12' style='display:none;'>"+
					                     "<div class='input-group col-sm-12'>"+
						                 	   "<span class='input-group-addon'>联系人员</span>"+
								               "<input class='form-control waypointContacts' />"+
						                 "</div>"+
					                "</div>"+
					                "<div class='col-sm-12' style='display:none;'>"+
					                       "<div class='input-group col-sm-12'>"+
						                 	    "<span class='input-group-addon'>联系电话</span>"+
								            	"<input class='form-control waypointPhone'  required/>"+
						                   "</div>"+
					                "</div>"+
					      "</div>"+
				      "<div class='input-group'>"+
	               	 //	"<label><img src='"+ctx+"/assets/css/images/minus_8.png' class=' waypointIcon subWaypoint' style='cursor:pointer;' title='删除途径地' index='waypoint"+count+"'/></label>"+
	             	    "<label><span class='glyphicon glyphicon-minus waypointIcon subWaypoint' style='cursor:pointer;' title='删除途径地' index='waypoint"+count+"'></span></label>"+
	               	 	"</div>"+
	             "</div>";
		 $("#waypointItem").append(content); 
		 $(".addWaypoint").unbind().click(function(){
			 $(".addAddress").click();
			 last=false;
		 });
		 $(".subWaypoint").unbind().click(function(){
			 count--;
			 pointIndex--;
			 
				$(this).parent().parent().parent().remove();
				var index1 = end.attr("index");
				end.attr("index",index1-1);
				/*
				var p1 = new BMap.Point(start[0],start[1]);
				var p2 = new BMap.Point(end[0],end[1]);
				freight_driving.search(p1, p2,{waypoints:way});
				//$('#'+index).remove();
				*/
				var arr = $(".subWaypoint");
				for(var i=0;i<arr.length;i++){
					$(arr[i]).attr("index",("waypoint"+(i+1)));
				}
				var arr = $(".wayAddress");
				for(var i=0;i<arr.length;i++){
					if(i==0){
						$(arr[i]).attr("id","start");
					}else if(i==(arr.length-1)){
						$(arr[i]).attr("id","end");
					}else{
						$(arr[i]).attr("id","waypoint"+(i+1));
					}
				}
				var address = $(".waypointAddress");
				for(var i=0;i<address.length;i++){
					$(address[i]).attr("index",i);
				}
				var temp = $(this).parent().parent().parent().find(".waypointAddress").attr("index");
				freight_points.splice(temp,1);
				 freight_map2.clearOverlays();
				 flag=true;
				  index=0;
				  distance=[];
				  timeStr=[];
				 for(var i=0;i<freight_points.length-1;i++){
					  freight_driving.search(freight_points[i],freight_points[i+1]);
				  }	 
				 
				 
		  });
		 
		var end = $("#end").find("#freight_destination");
		var address=end.val();
		end.val("");
		var lng=end.attr("waypointlng");
		end.attr("waypointlng","");
		var lat=end.attr("waypointlat");
		end.attr("waypointlat","");
		var phone=$("#end").find("#phone").val();
		$("#end").find("#phone").val("");
		$("#end").find(".showPhone").empty();
		end.attr("waypointlat","");
		var contacts=$("#end").find("#contacts").val()
		$("#end").find("#contacts").val("");
		$("#end").find(".showContacts").empty();
		var way = $("#waypoint"+count);
		way.find(".waypointAddress").val(address);
		way.find(".waypointAddress").attr("waypointLng",lng);
		way.find(".waypointAddress").attr("waypointLat",lat);
		way.find(".waypointContacts").val(contacts);
		way.find(".waypointPhone").val(phone);
		way.find(".showContacts").text(contacts);
		way.find(".showPhone").text(phone);
		var index2 = way.find(".waypointAddress").attr("index");
		var index1 = end.attr("index");
		way.find(".waypointAddress").attr("index",index1);
		end.attr("index",index2);
		 $(".waypointIcon").mouseover(function(){
			 $(this).addClass("icon-2x");		
		 });
		 $(".waypointIcon").mouseout(function(){
			 $(this).removeClass("icon-2x");		
		 });
		 
		 showData($("#freight_destination"));
	});
	

	$("#freight_companyId").change(function(){
		var select = $("#truckTypeId");
		if($(this).val()!=""){
		$.get(ctx+'/freight/findByTruckTypeCompanyId',{'companyId':$(this).val()},function(data){
		    select.children('option').remove();
		    var truckTypes = data.truckTypes;
		    if(truckTypes.length==0){
		    	select.children('option').remove()
				var content = "<option value=''>此公司没有货车类型</option>";
		    	select.append($(content));
		    	$("#budgetPay").val("");
		    	$("#startPrice").val("");
		    	$("#mileagePrice").val("");
		    	$("#runTimePrice").val("");
		    	$("#runTime").val("");
		    	$("#mileage").val("");
		    	$(".runTime").text("");
		    	$(".mileage").text("");
		    	getFreightEmployee();
		    }
		    for(var i=0;i<truckTypes.length;i++){
		    	
		    	var str = '';
		    	if(truckTypes[i].cangointotown){
		    		str='--入城';
		    	}
		    	var content = "<option value='"+truckTypes[i].id+"'>"+truckTypes[i].typeName+str+"</option>";
		    	select.append($(content));
		    	$("#truckTypeId").change();
		    }
			
		},'json');
		}else{
			select.children('option').remove()
			var content = "<option value=''>请先选择公司</option>";
	    	select.append($(content));
		}
	});
	 
	$("#freight_passengerName").change(function(){
		$("#start").find(".waypointContacts").val($(this).val());
		$("#start").find(".showContacts").text($(this).val());
	}); 
	 
	$("#freight_passengerPhone").change(function(){
		$.get(ctx+'/member/findByPhone',{'phone':$(this).val(),'couponType':'freight'},function(data){
			if(data.passenger!=null){
				$("#freight_membertype").text("");
				$("#freight_companyName").val(data.passenger.companyName);
				$("#freight_passengerId").val(data.passenger.id);
				$("#freight_passengerName").val(data.passenger.name);
				$("#start").find(".waypointContacts").val(data.passenger.name);
				$("#start").find(".waypointPhone").val(data.passenger.phone);
				$("#start").find(".showContacts").text(data.passenger.name);
				$("#start").find(".showPhone").text(data.passenger.phone);
				if(data.passenger.inBlackList){
					$("#freight_membertype").html("黑名单");
					isBlack=true;
				}else{
					$("#freight_membertype").html(data.passenger.typeStr+(data.passenger.grade_name==null || data.passenger.grade_name==""?"":("-"+data.passenger.grade_name)));
				}
				$("#freight_clientVirtual").text(data.passenger.drawMoney+"元");
				$("#freight_companyId option").each(function(index,element){
				  	if($(element).attr("value")==data.passenger.companyId){
				 		$(element).attr("selected","selected");
				 		$("#freight_companyId").change();
				 		return false;
				 	}
				});
				if(data.coupons!=null&&data.coupons.length>0){
					var text="";
					for(var i=0;i<data.coupons.length;i++){
						if(data.coupons[i].couponRule.couponType=="freight"){
							text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
						}
					}
					$("#freight_couponId").empty();
					if(text!=""){
						$("#couponInput").css("display","block");
						$("#freight_couponId").append(text);
					}
				}else{
					$("#couponInput").css("display","none");
					$("#freight_couponId").empty();
				}
			}else{
				$("#couponInput").css("display","none");
				$("#freight_couponId").empty();
				$("#freight_membertype").text("新客户");
				$("#freight_passengerName").val("先生/女士");
				$("#start").find(".waypointContacts").val($("#freight_passengerName").val());
				$("#start").find(".waypointPhone").val($("#freight_passengerPhone").val());
				$("#start").find(".showContacts").text($("#freight_passengerName").val());
				$("#start").find(".showPhone").text($("#freight_passengerPhone").val());
			}
			
		});
		
		if(timeStr!=null&&timeStr.length>0&&distance!=null&&distance.length>0){
			 $.post(ctx+"/freight/getPrice",
					   {
				     companyId:ismainCompany?$("#freight_companyId").val():"",
				     truckTypeId:$("#truckTypeId").val(),
					    time:timeStr.join(","),
					    mileage:distance.join(",")},function(data){
					    	if(data.success){
					    		$("#freight_budgetPay").val(data.money);
						    	$("#freight_startPrice").val(data.startPrice);
						    	$("#freight_mileagePrice").val(data.mileagePrice);
						    	$("#freight_runTimePrice").val(data.travelTimePrice);
						    	$("#freight_runTime").val(data.travelTime);
						    	$("#freight_mileage").val(data.mileage);
					    		$(".freight_runTime").text("预计时间:"+data.travelTime+"分钟");
						    	$(".freight_mileage").text("预计路程:"+data.mileage+"公里");
					    	}else{
					    		$(".freight_runTime").text("预估价格失败");
					    		$("#freight_budgetPay").val(data.money);
					    	}
					    },"json");
		}
		
	});	
	
	$("#truckTypeId").change(function(){
		if(freight_points[0]){
			getFreightEmployee();
		}
		if(timeStr!=null&&timeStr.length>0&&distance!=null&&distance.length>0){
			 $.post(ctx+"/freight/getPrice",
					   {
				 companyId:ismainCompany?$("#freight_companyId").val():"",
				 		truckTypeId:$("#truckTypeId").val(),
					    time:timeStr.join(","),
					    mileage:distance.join(",")},function(data){
					    	if(data.success){
					    		$("#freight_budgetPay").val(data.money);
						    	$("#freight_startPrice").val(data.startPrice);
						    	$("#freight_mileagePrice").val(data.mileagePrice);
						    	$("#freight_runTimePrice").val(data.travelTimePrice);
						    	$("#freight_runTime").val(data.travelTime);
						    	$("#freight_mileage").val(data.mileage);
					    		$(".freight_runTime").text("预计时间:"+data.travelTime+"分钟");
						    	$(".freight_mileage").text("预计路程:"+data.mileage+"公里");
					    	}else{
					    		$(".freight_runTime").text("预估价格失败");
					    		$("#freight_budgetPay").val(data.money);
					    	}
					    },"json");
		}
	});
	$("#freight_close_modal").click(function(){
			// issubmit=true;
			 window.close();
	});

	$("#freightfixPrice").click(function(e){
		if(this.checked){
			$("#freightfixPrice_div").slideDown();
		}
		else{
			$("#freightfixPrice_div").slideUp();
		}
	});


	//下单
	var createflag = false;
	$("#freight_saveOrder").click(function(){
		if(createflag){
			return ;
		}
		var temp=$("input[name='freihgt_checkDriver']:checked").val();
		var tempEmployId=null;
		if(temp){
			tempEmployId=temp;
		}
		var ways = $(".wayAddress");
		var temp="";
		for(var i=0;i<ways.length;i++){
			if(i==(ways.length-1)){
				var address = $(ways[i]).find($(".waypointAddress")).val();
				var person = $(ways[i]).find($(".waypointContacts")).val();
				var phone = $(ways[i]).find($(".waypointPhone")).val();
				var waypointLng = $(ways[i]).find($(".waypointAddress")).attr("waypointLng");
				var waypointLat = $(ways[i]).find($(".waypointAddress")).attr("waypointLat");
				 temp=temp+'{"phone":"'+phone+'",';
				 temp=temp+'"contacts":"'+person+'",';
				 temp=temp+'"address":"'+address+'",';
				 temp=temp+'"lng":"'+waypointLng+'",';
				 temp=temp+'"lat":"'+waypointLat+'",';
				 temp=temp+'"sequence":"'+(i)+'"}';
			}else{
				var address = $(ways[i]).find($(".waypointAddress")).val();
				var person = $(ways[i]).find($(".waypointContacts")).val();
				var phone = $(ways[i]).find($(".waypointPhone")).val();
				var waypointLng = $(ways[i]).find($(".waypointAddress")).attr("waypointLng");
				var waypointLat = $(ways[i]).find($(".waypointAddress")).attr("waypointLat");
				 temp=temp+'{"phone":"'+phone+'",';
				 temp=temp+'"contacts":"'+person+'",';
				 temp=temp+'"address":"'+address+'",';
				 temp=temp+'"lng":"'+waypointLng+'",';
				 temp=temp+'"lat":"'+waypointLat+'",';
				 temp=temp+'"sequence":"'+(i)+'"},';
			}
			
		}
		var waypoints = "["+temp+"]";

		if($("#freight_companyId").val()==''){
			$.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
			return;
		}

		if($("#freight_passengerPhone").val()==''){
			$.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#truckTypeId").val()==""){
			$.scojs_message("请选择货车类型", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#freight_orderMemo").val()!=""&&$("#freight_orderMemo").val().length>100){
			$.scojs_message("输入的备注信息过长", $.scojs_message.TYPE_ERROR);
			return;
		}
		
		if($("#freight_passengerName").val()==''){
			$.scojs_message("请填写客户姓名", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#freight_startAddress").val()==''){
			$.scojs_message("请填写起始地", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#freight_destination").val()==''){
			$.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#phone").val()==""){
			$.scojs_message("请填写目的地联系人电话", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#freight_startTime").val()==""){
			$.scojs_message("请填写预约时间", $.scojs_message.TYPE_ERROR);
			return;
		}else{
			if(new Date($("#freight_startTime").val().replace("-","/")).getTime()-new Date().getTime()<0){
				$("#freight_startTime").val(new Date().Format("yyyy-MM-dd hh:mm"));
			}		
		}
		if(receivedPay){
			if($("[name='payMount']").val()==""){
				$.scojs_message("请填写回款金额", $.scojs_message.TYPE_ERROR);
				return;
			}
		}

		if($("#freightfixPrice").length>0 && $("#freightfixPrice")[0].checked){
			if($("#freightfixPriceMoney").val()==""){
				$.scojs_message("请填写定价金额", $.scojs_message.TYPE_ERROR);
				return false;
			}
			var moneyReg=/^(\d+)(.[0-9]{0,1})?$/;
			if(!moneyReg.test($("#freightfixPriceMoney").val())){
				$.scojs_message("请填写正确的定价金额，如：39.9", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}
		createflag = true;
			$.ajax({
	             type: "POST",
	             url: ctx+"/freight/create",
	             data: {
	            	 passengerId:$("#freight_passengerId").val(),
	            	 passengerName:$("#freight_passengerName").val(),
	            	 passengerPhone:$("#freight_passengerPhone").val(),
	            	 companyId:$("#freight_companyId").val(),
	            	 companyName:$('#freight_companyId').find("option:selected").text(),
	            	 truckTypeId:$("#truckTypeId").val(),
	            	 truckTypeName:($('#truckTypeId').find("option:selected").text()).split("--").length>1?($('#truckTypeId').find("option:selected").text()).split("--")[0]:($('#truckTypeId').find("option:selected").text()).split("--")[0],
	            	 startTime:$("#freight_startTime").val(),
	            	 budgetPay:$("#freight_budgetPay").val(),
	            	 preStartPrice:$("#freight_startPrice").val(),
	            	 preMileagePrice:$("#freight_mileagePrice").val(),
	            	 preRunTimePrice:$("#freight_runTimePrice").val(),
	            	 preRunTime:$("#freight_runTime").val(),
	            	 preMileage:$("#freight_mileage").val(),
	            	 couponId:$("#freight_couponId").val(),
	            	 flitting:flitting,
	            	 receipt:receipt,
	            	 receivedPay:receivedPay,
	            	 payMount:$("[name='payMount']").val(),
	            	 memo:$("#freight_orderMemo").val(),
	            	 employId:tempEmployId,
					 fixPrice:$("#freightfixPrice").is(':checked'),
					 fixPriceMoney:$("#freightfixPrice").is(':checked')?$("#freightfixPriceMoney").val():"",
	            	 waypoint:waypoints
	             },	
	             dataType: "json",
	             success: function(data){
					 createflag = false
	            	 if(data.success){
	            		 $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
	            		 $('#dialog_order').modal("hide");
	            		 issubmit=true;
	            		 window.opener.location.reload(true);
	            		 setTimeout(function(){
		            		 window.close();
		     				},500);
	            		 
	            	 }else{
	            		 $.scojs_message(data.message.split(":").length>1?data.message.split(":")[1]:data.message, $.scojs_message.TYPE_ERROR);
	            	 }
	             },
				error: function () {
					createflag = false;
				}
	      });
	});
	
	
	
	
	
	//定位
	$("#btn-startAddress").click(function(){
		if($("#startAddress").val()==''){
			$.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
		}else{
			freight_map2.clearOverlays();
			var local = new BMap.LocalSearch(freight_map2, {
				renderOptions:{map: freight_map2, autoViewport:true}
			});
			local.search($("#startAddress").val());
			
			local.setInfoHtmlSetCallback(function(poi,html){
		    	   var str = ($(html).text().substr(4).split("电话"))[0];
		    	   var string;
		    	   if(str.indexOf("段")==-1){
			    		  if(str.indexOf("路")==-1){
			    			  if(str.indexOf("街")==-1){
			    				  if(str.indexOf("号")==-1){
			    					  string =str;
			    				  }else{
			    					  string=str.substring(0,str.indexOf(/\d+号/.exec(str)[0]));
			    				  }
			    			  }else{
			    				 string = str.substring(0,str.indexOf("街")+1);
			    			  }
			    		  }else{
			    			  string = str.substring(0,str.indexOf("路")+1);
			    		  }
			    	   }else{
			    		   string = str.substring(0,str.indexOf("段")+1);
			    	   }	
		    	   
		    	   $("#startAddress").val(string+poi.marker.getTitle());
		    	   $("#startLng").val(poi.marker.point.lng);
			       $("#startLat").val(poi.marker.point.lat);
			        start[0]=poi.marker.point.lng;
			        start[1]=poi.marker.point.lat;
			    	var title = poi.marker.getTitle();
			        var markers = freight_map2.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
			        if(end.length!=0){
			        	var startPoint=new BMap.Point(start[0], start[1]);
						var endPoint=new BMap.Point(end[0],end[1]);
						freight_driving.search(startPoint, endPoint);
					    poi.marker.hide(); 
			        }
		    });
		}
	});
	
	$("#btn-destination").click(function(){
		if($("#destination").val()==''){
			$.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
		}else{
			freight_map2.clearOverlays();
			var local = new BMap.LocalSearch(freight_map2, {
	    	  renderOptions:{map: freight_map2, autoViewport:true}
	    	});
		    local.search($("#destination").val());
		    local.setInfoHtmlSetCallback(function(poi,html){
		    	 var str = ($(html).text().substr(4).split("电话"))[0];
		    	   var string;
		    	   if(str.indexOf("段")==-1){
			    		  if(str.indexOf("路")==-1){
			    			  if(str.indexOf("街")==-1){
			    				  if(str.indexOf("号")==-1){
			    					  string =str;
			    				  }else{
			    					  string=str.substring(0,str.indexOf(/\d+号/.exec(str)[0]));
			    				  }
			    			  }else{
			    				 string = str.substring(0,str.indexOf("街")+1);
			    			  }
			    		  }else{
			    			  string = str.substring(0,str.indexOf("路")+1);
			    		  }
			    	   }else{
			    		   string = str.substring(0,str.indexOf("段")+1);
			    	   }	
		    	   $("#destination").val(string+poi.marker.getTitle());
		    	   $("#endLng").val(poi.marker.point.lng);
			       $("#endLat").val(poi.marker.point.lat);
			        end[0]=poi.marker.point.lng;
			        end[1]=poi.marker.point.lat;
			    	var title = poi.marker.getTitle();
			        var markers = freight_map2.getOverlays();
					for(var i=0;i<markers.length;i++){
						markers[i].show();
					}
			        if(start.length!=0){
			        	var startPoint=new BMap.Point(start[0], start[1]);
						var endPoint=new BMap.Point(end[0],end[1]);
						freight_driving.search(startPoint, endPoint);
					    poi.marker.hide();
			        }
		    });
		}
	});
	
	//自动补全交付地点
	/*
	$("#destination").AutoComplete({
	    data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
	    itemHeight: 24,
	    width:"auto",
	    async: true,
	    listStyle: "custom",
	    emphasis: false,
	    matchHandler: function(keyword, data){
	        return true;
	    },
	    createItemHandler: function(index, data){
	    	if(data.address.length>14){
        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
        	}
            return "<span title='"+data.address+"'>"+data.address+"</span>";
	    },
	    afterSelectedHandler: function(data){
	    	var address = (data.address).split(" ");
	    	$("#destination").val(address[0]);
	    	$("#endLat").val(data.latitude);
	    	$("#endLng").val(data.longitude);
	    	if($("#destination").val()!=""){
				var startPoint=new BMap.Point(parseFloat($("#startLng").val()),parseFloat($("#startLat").val()));
				var endPoint=new BMap.Point(parseFloat($("#endLng").val()),parseFloat($("#endLat").val()));
				freight_map2.centerAndZoom(startPoint, 10); 
				freight_driving.search(startPoint, endPoint);
			}		
	        markerComplete(data.longitude,data.latitude);
	    }
	}).AutoComplete('show');
/*
	$("#startAddress").AutoComplete({
	    data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
	    itemHeight: 24,
	    max:1,
	    width: "auto",
	    async: true,
	    listStyle: "custom",
	    emphasis: false,
	    matchHandler: function(keyword, data){
	        return true;
	    },
	    createItemHandler: function(index, data){
	    	if(data.address.length>14){
        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
        	}
            return "<span title='"+data.address+"'>"+data.address+"</span>";
	    },
	    afterSelectedHandler: function(data){
	    	var address = (data.address).split(" ");
	    	$("#startAddress").val(address[0]);
	    	$("#startLat").val(data.latitude);
	    	$("#startLng").val(data.longitude);
	        if($("#destination").val()!=""){
	    		var startPoint=new BMap.Point(parseFloat($("#startLng").val()),parseFloat($("#startLat").val()));
	    		var endPoint=new BMap.Point(parseFloat($("#endLng").val()),parseFloat($("#endLat").val()));
	    		freight_map2.centerAndZoom(startPoint, 10); 
	    		freight_driving.search(startPoint, endPoint);	
	    	}
	        markerComplete(data.longitude,data.latitude);
	    }
	}).AutoComplete('show');
	*/
	$(".colse").click(function(){
		$('#myModal').modal("hide");
	});
	$("#Address").AutoComplete({
	    data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
	    itemHeight: 24,
	    max:1,
	    width: "auto",
	    async: true,
	    listStyle: "custom",
	    emphasis: false,
	    matchHandler: function(keyword, data){
	        return true;
	    },
	    createItemHandler: function(index, data){
	    	if(data.address.length>14){
        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
        	}
            return "<span title='"+data.address+"'>"+data.address+"</span>";
	    },
	    afterSelectedHandler: function(data){
	    	var length = freight_points.length;
	    	var address = tempInput.find(".waypointAddress");
	    	address.attr("waypointLat",data.latitude);
	    	address.attr("waypointLng",data.longitude);
    		address.val(data.address);
    		$("#Address").val(data.address);
	    	var tempIndex=parseInt(address.attr("index"));
	    	var point=new BMap.Point(data.longitude,data.latitude);
	    	   index=0;
			   flag=true;
			   pointObj=[];
			  distance=[];
			  timeStr=[];
			   if(freight_points[tempIndex]!=undefined){
	    		   freight_points.splice(tempIndex,1,point);
	    	   }else{
	    		   freight_points[length]=point;
	    	   }
			 if(freight_points.length!=1){
				 freight_map2.clearOverlays();           
				  for(var i=0;i<freight_points.length-1;i++){
					  freight_driving.search(freight_points[i],freight_points[i+1]);
				  }	
			 }else{
				 getFreightEmployee();
				 freight_map2.clearOverlays();    
				 var marker = new BMap.Marker(point); 
				 freight_map2.addOverlay(marker);
			 } 
	        markerComplete(data.longitude,data.latitude);
	    }
	}).AutoComplete('show');

});
